//
//  CircleViewController.swift
//  V2ex-Swift
//
//  Created by Jasper on 2/28/16.
//  Copyright © 2016 Fin. All rights reserved.
//

import UIKit
//import ObjectMapper
import DOPDropDownMenu_Enhanced
import SVProgressHUD
import MJRefresh
import AVOSCloud

fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class PictureViewController: RootViewController, UITableViewDataSource, UITableViewDelegate, DOPDropDownMenuDelegate, DOPDropDownMenuDataSource {
    
    struct LouHeight {
        var start: Int
        var end: Int
    }
    
    @IBOutlet weak var pictureTableView: UITableView!
    
    var dropMenu: DOPDropDownMenu?
    
//    var regionArray = [Region]()
    var countrys = [Country]()
    var orCountrys = [Country]()
    
    var statusArray = [String]()
    var heightArray = [LouHeight]()
    
//    var currentCity: City?
    var currentAllCiyts: AllCity?
    var currentCountry: Country?
    
    var currentStaus: String?
    var currentHeight: LouHeight?
    
    var towerArray = [Tower]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "排行"
        tabBarController?.tabBar.selectedItem?.selectedImage = UIImage(named: "tabbar_picture_selected")
        self.navigationController?.navigationBar.tintColor = UIColor.white
        
//        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "摩天指数", style: .Plain, target: self, action: #selector(leftClicked(_:)))
        
         pictureTableView.tableFooterView = UIView()
        
        statusArray = ["所有状态","建成+封顶","建成", "封顶", "在建",
//                       "预备",
                       "规划", "搁置"]
        heightArray = [LouHeight(start: 0, end: 2000),
//                       LouHeight(start: 100, end: 200),
                       LouHeight(start: 250, end: 300),
                       LouHeight(start: 300, end: 400),
                       LouHeight(start: 400, end: 500),
                       LouHeight(start: 500, end: 600),
                       LouHeight(start: 600, end: 2000),
//                       LouHeight(start: 700, end: 800),
//                       LouHeight(start: 800, end: 900),
//                       LouHeight(start: 900, end: 1000)
        ]
        
        currentStaus = statusArray.first
        currentHeight = heightArray.first
        
        let menu = DOPDropDownMenu(origin: CGPoint(x: 0, y: 0), andHeight: 44)
        menu?.delegate = self
        menu?.dataSource = self
        view.addSubview(menu!)
        dropMenu = menu
        
        requestCountry()
        
        pictureTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { 
            self.requestData(true)
        })
        
        pictureTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.requestData(false)
        })
        
        requestData(true)
        
        
        updateImag() // 测试用途，一定要注释掉
    }
    
    func updateImag() {  // 上传图片
        
        let fileManager = FileManager()
        let url = URL(fileURLWithPath: "/Users/jasper/Desktop/outputTinypng")
        
        let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles) { (url: URL, error: Error?) -> Bool in
            if error != nil {
                return false
            } else {
                return true
            }
        }
        
        
        for url in enumerator! {
            
            let subUrl = url as! URL
            
            let img = UIImage(contentsOfFile: subUrl.absoluteString);
            
//            let img = UIImage(urlString: subUrl.absoluteString)
            
            let picture = Picture()
            picture.user = AVUser.current()
            picture.isShow = true
            picture.tower = Tower(objectId: "578f2fd52e958a0054523234")// 填写
//            picture.tower = Tower(outDataWithObjectId: "5732e8dc71cfe4006cc818f0") // 填写
            picture.name = "Al Noor 大厦" // 填写
            
            picture.descriptions = ""
            let data = UIImageJPEGRepresentation(img!, 0.8)
            picture.file = AVFile(data: data!)
            
            picture.saveInBackground { (succed: Bool, error: Error?) in
                if succed {
                    print("上传成功----\(subUrl)")
                } else {
                    print("上传失败~~~~\(subUrl)")
//                    SVProgressHUD.showSuccessWithStatus(error?.localizedDescription)
                }
            }
        }
    }
    
    func leftClicked(_ sender: UIBarButtonItem) {
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        regionArray = DataCenter.sharedInstance.commonRegin
//        rebuidRegionArray()
//        if regionArray.count == 0 {
//            requestRegion()
//        }
        if self.orCountrys.count == 0 {
            requestCountry()
        }
    }
    
    @IBAction func addTowerClicked(_ sender: UIBarButtonItem) {
        if AVUser.current() == nil { // 没登录
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController");
            loginViewController.hidesBottomBarWhenPushed = true;
            self.navigationController?.pushViewController(loginViewController, animated: true)
        } else {
            if countrys.count == 0 {
                SVProgressHUD.showError(withStatus: "网络忙，请稍后再试！")
                return
            }
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let submitTowerVC = storyboard.instantiateViewController(withIdentifier: "SubmitTowerViewController") as! SubmitTowerViewController;
            submitTowerVC.countrys = orCountrys;
            submitTowerVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(submitTowerVC, animated: true)
        }
        
    }
    
//    func rebuidRegionArray() {
//        if regionArray.count > 0 {
//            regionArray.removeLast()
//            let region = Region()
//            region.name = "所有"
//            region.citys = [City]()
//            regionArray.insertAsFirst(region)
//            currentCity = regionArray.first?.citys?.first
//            dropMenu?.reloadData()
//        }
//    }

    func requestData(_ header: Bool) {
        SVProgressHUD.show()
        let query: AVQuery = Tower.query()
        query.includeKey(kTowerKeyAllCity)
        query.order(byDescending: kTowerKeyHeight)
        query.whereKey(kTowerKeyIsShow, equalTo: true)
        query.limit = kNetPageSize
 
        if currentAllCiyts?.name != nil { // 全部时 不筛选
            let isExit = currentAllCiyts?.name?.contains("所有")
            if (isExit!) {
                query.whereKey(kTowerKeyCountry, equalTo: currentCountry?.name)  // 筛选哪个国家
            } else {
                query.whereKey(kTowerKeyAllCity, equalTo: currentAllCiyts)  // 筛选是哪个城市
            }
        }
        
        if currentStaus == "建成+封顶" {
            query.whereKey(kTowerKeyStatus, containedIn: ["建成","封顶"]) // 筛选状态
        } else if currentStaus == "所有状态" {
            // 不筛选
        } else {
            query.whereKey(kTowerKeyStatus, containedIn: [currentStaus!]) // 筛选状态
        }
        
        query.whereKey(kTowerKeyHeight, greaterThan: currentHeight?.start) //equalto
        query.whereKey(kTowerKeyHeight, lessThan: currentHeight?.end)
        
        if !header {
            let top = towerArray.last
            let height = top?.object(forKey: kTowerKeyHeight)
            if height != nil {
                query.whereKey(kTowerKeyHeight, lessThan: height)  // 复写了上面的 lessThan
            }
        }
        
        query.findObjectsInBackground { (objects: [Any]?, error: Error?) in
            if error == nil && objects != nil {
                if let towers = objects as? [Tower] {
                    SVProgressHUD.dismiss()
                    if header {
                        self.towerArray.removeAll()
                    }
                    self.towerArray += towers
                   self.pictureTableView.reloadData()
                } else {
                    SVProgressHUD.showError(withStatus: "获取列表失败")
                }
            } else {
                SVProgressHUD.showError(withStatus:error?.localizedDescription)
            }
            
            self.pictureTableView.mj_header.endRefreshing()
            if objects != nil && objects?.count < kNetPageSize {
                self.pictureTableView.mj_footer.endRefreshingWithNoMoreData()
                
            } else {
                if header {
                    self.pictureTableView.mj_footer.resetNoMoreData()
                } else {
                    self.pictureTableView.mj_footer.endRefreshing()
                }
            }
        }
    }
    
//    func requestRegion() {
//        
//        let query: AVQuery = Region.query()
//        query.includeKey(kRegionKeyCity)
//        query.orderByAscending(kRegionKeyOrder)
//        
//        query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) in
//            
//            if error == nil && objects != nil {
//                if let regins = objects as? [Region] {
//                    self.regionArray = regins
//                    DataCenter.sharedInstance.commonRegin = regins
//                    self.rebuidRegionArray()
//                } else {
////                    SVProgressHUD.showErrorWithStatus("获取列表失败")
//                }
//            } else {
////                SVProgressHUD.showErrorWithStatus(error?.localizedDescription)
//            }
//        }
//    }
    
    func rebuidRegionCountry() {
        
        var temCountrys = [Country]();
        for subCountry in countrys {
            let mCountry = subCountry
            var allCitys = subCountry.allCitys
            if allCitys?.count > 1 {
                let subCity = AllCity()
                subCity.name = "\(subCountry.name!)-所有"
                allCitys?.insert(subCity, at: 0)
//                allCitys?.insertAsFirst(subCity)
            }
            mCountry.allCitys = allCitys
            temCountrys.append(mCountry)
        }
        
        if temCountrys.count > 0 {
            let country = Country()
            country.name = "全球"
            country.allCitys = [AllCity]()
            temCountrys.insert(country, at: 0)
//            temCountrys.insertAsFirst(country)
            countrys = temCountrys
            currentAllCiyts = countrys.first?.allCitys?.first
            currentCountry = countrys.first
            dropMenu?.reloadData()
        }
    }
    
    
    func requestCountry() {
        SVProgressHUD.show(withStatus: "数据请求中...")
        let query: AVQuery = Country.query()
        query.includeKey(kCountryKeyAllCitys)
        query.order(byAscending: kCountryKeyOrder)
        
        query.findObjectsInBackground { (objects: [Any]?, error: Error?) in
            
            if error == nil && objects != nil {
                if let mCountry = objects as? [Country] {
                    self.orCountrys = mCountry
                    self.countrys = mCountry
                    self.rebuidRegionCountry()
                } else {
                    SVProgressHUD.showError(withStatus:"获取列表失败")
                }
            } else {
                SVProgressHUD.showError(withStatus:error?.localizedDescription)
            }
        }
    }
    
    // MARK:DOPDropDownMenuDelegate
    
    func numberOfColumns(in menu: DOPDropDownMenu!) -> Int {
        return 3
    }
    
    func menu(_ menu: DOPDropDownMenu!, numberOfRowsInColumn column: Int) -> Int {
        if column == 0 {
            return countrys.count
        } else if column == 1 {
            return heightArray.count
        } else { //2
            return statusArray.count
        }
    }
    
    /**
     *  返回 menu 第column列 每行title
     */
    func menu(_ menu: DOPDropDownMenu!, titleForRowAt indexPath: DOPIndexPath!) -> String! {
        if indexPath.column == 0 {
            if countrys.count == 0 {
                return ""
            }
            return countrys[indexPath.row].name
        } else if indexPath.column == 1 {
            let louHeight = heightArray[indexPath.row]
            if louHeight.start == 0 {
                return "所有高度"
            } else if louHeight.start == 600 {
                return "600以上"
            } else {
                return "\(louHeight.start)-\(louHeight.end)"
            }
        } else {
            return statusArray[indexPath.row]
        }
    }
    
    func menu(_ menu: DOPDropDownMenu!, didSelectRowAt indexPath: DOPIndexPath!) {
        AVAnalytics.event("图库筛选\(indexPath.column)")
        if indexPath.column == 0 {
            if indexPath.row == 0 {
                // 全部
                currentAllCiyts = countrys.first?.allCitys?.first
                currentCountry = countrys.first
            } else {
                if indexPath.item == -1 { // 只点了左边
                    return
                }
                currentAllCiyts = countrys[indexPath.row].allCitys![indexPath.item]
                currentCountry = countrys[indexPath.row]
            }
        } else if indexPath.column == 1 {
            currentHeight = heightArray[indexPath.row]
        } else {
            currentStaus = statusArray[indexPath.row]
        }
        requestData(true)
    }
    
    func menu(_ menu: DOPDropDownMenu!, numberOfItemsInRow row: Int, column: Int) -> Int {
        if column == 0 {
           return countrys[row].allCitys!.count
        }
        return 0
    }
    
    func menu(_ menu: DOPDropDownMenu!, titleForItemsInRowAt indexPath: DOPIndexPath!) -> String! {
        if indexPath.column == 0 {
//            return regionArray[indexPath.row].citys.name
            return countrys[indexPath.row].allCitys![indexPath.item].name
//            return "多喝点"
        }
        return nil
    }
    
    func menu(_ menu: DOPDropDownMenu!, detailTextForRowAt indexPath: DOPIndexPath!) -> String! {
        if indexPath.column == 0 {
            return "\(countrys[indexPath.row].allCitys!.count)"
        }
        return nil
    }
    
    // MARK:UITableViewDataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
//        return (areas?.count)!
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return towerArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PictureMainCell", for: indexPath) as! PictureMainCell
        let tower = towerArray[(indexPath as NSIndexPath).row]
        cell.refreshView(tower, index: (indexPath as NSIndexPath).row+1)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    
    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        if segue.identifier == "PictureShowViewController" {
            let replyVC = segue.destination as! PictureShowViewController
            replyVC.hidesBottomBarWhenPushed = true;
            let cell = sender as! UITableViewCell
            if let indexPath = pictureTableView.indexPath(for: cell) {
                let tower = towerArray[(indexPath as NSIndexPath).row]
                replyVC.tower = tower
            }
        }
    }
    
    // 创建
    
    func createData() {
        let tower = Tower()
        tower.name = "哈利法塔"
        tower.city = City()
        tower.height = 828.00
        tower.floor = 163
        tower.timeFinish = 2010
        tower.purpose = "写字楼 酒店 住宅"
        tower.status = "建成"
        tower.descriptions = ""
        
        tower.saveInBackground { (succed: Bool, error: Error?) in
            if succed {
                
            } else {
                SVProgressHUD.showError(withStatus: error?.localizedDescription)
            }
        }
    }
}


//func parseDatas() {
//    let path = NSBundle.mainBundle().pathForResource("citys", ofType: "json")
//    if let data = NSData(contentsOfFile: path!) {
//        if let jsonString =  NSString(data: data, encoding: NSUTF8StringEncoding) {
//            citysObject = Mapper<datas>().map(jsonString)
//            print(citysObject)
//        }
//        
//    }
//}

//class datas:Mappable {
//    var data: [Areas]?
//    required init?(_ map: Map) {
//        
//    }
//    func mapping(map: Map) {
//        data		    <- map["data"]
//    }
//}
//
//
//class Areas: Mappable {
//    var id: String?
//    var name: String?
//    var description: String?
//    var city: [Citys]?
//    
//    required init?(_ map: Map) {
//        
//    }
//    
//    func mapping(map: Map) {
//        id		    <- map["id"]
//        name		<- map["name"]
//        description	<- map["description"]
//        city        <- map["city"]
//    }
//}
//
//
//class Citys: Mappable {
//    var id: String?
//    var name: String?
//    var description: String?
//    var icon: String?
//    
//    required init?(_ map: Map) {
//        
//    }
//    
//    func mapping(map: Map) {
//        id		    <- map["id"]
//        name		<- map["name"]
//        description	<- map["description"]
//        icon        <- map["icon"]
//    }
//}

